/* eslint-disable */
import Vue from 'vue'
import axios from 'axios'
import Toast from '@components/toast'
import { errReport } from '@utils/report/index'
import { isObject } from '@utils/is'
import lotus from '@utils/lotus'
import CONSTS from '@/assets/const'

// axios默认配置
const AXIOS_DEFAULT_CONFIG = {
  timeout: 15000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
}

// 自定义上报类型
const type = ['ph_app_bus_req_succ', 'ph_app_bus_req_fail']

/** 自定义参数
 * options.system 系统参数
 * options.silent 是否静默报错
 **/
let options = {}

// 监控接口数据，输出日志到本地app，默认上报级别为2!  0表示“error”级别，1表示“warning”级别，2表示“info”级别 ，3表示“debug”级别
function interfaceMonitor(content, module, level = 2) {}

// 请求成功
function requestSuccess(request) {
  request.data = {
    system: options.system || {},
    data: request.data || {}
  }
  return request
}

// 请求失败
function requestFail(err) {
  Toast(`${err.message}(${err.config.url})`)
  return Promise.reject(err)
}

// 响应成功
function responseSuccess(response) {
  let { data: res } = response
  const system = res.system || {}
  // 网关获取uid/trace_id，自动添加到$user
  if (res.data && isObject(res.data.result_rows) && !res.data.result_rows.uid) {
    res.data.result_rows.uid = system.uid
    Vue.prototype.$user.uid = system.uid
    Vue.prototype.$user.traceId = system.trace_id
  }
  // 响应成功时，记录到日志
  const content = {
    _url_: response.config.url,
    param: response.config.data,
    retcode: res.result,
    retmsg: res.data || res.res_info,
    trace_id: system.trace_id || ''
  }

  // 未登录或登录已过期则跳回普惠App首页或分期乐App
  if (res.result === 10200007 || res.result === 10200005) {
    if (lotus.isPhApp) {
      // hack: 兼容 普惠App ios版本 跳转问题
      lotus.forward(CONSTS.PUHUIAPP_HOME_PAGE)
    } else {
      window.location.href = `${CONSTS.FENQILE_LOGIN_PAGE}?url=${encodeURIComponent(window.location.href)}`
    }
    return
  }

  if (res.result === 0 && res.data) {
    res = res.data
    if (res.result === 0 || res.result === '0') {
      // 业务请求成功，输出到日志
      interfaceMonitor(content, type[0])
      return res.result_rows
    } else if (!options.silent) {
      // 二维码失效 15360008 | 仅限新用户开通 15360012 | 有在途单 15360058, 15360059, 15360060
      Toast(res.res_info)
      if ([15360008, 15360012, 15360058, 15360059, 15360060].includes(res.result)) {
        setTimeout(() => {
          const url = lotus.isPhApp ? CONSTS.PUHUIAPP_HOME_PAGE : CONSTS.MY_PAGE
          lotus.forward(url, { isCloseCrtPage: 1 })
        }, 1500)
        return
      }
      // 分期乐App不支持该业务，重定向到App首页
      if ([1536110].includes(res.result)) {
        setTimeout(() => {
          lotus.forward(CONSTS.HOME_PAGE)
        }, 1500)
        return
      }
    }
  } else if (!options.silent) {
    responseError(response, res)
  }
  return Promise.reject(res)
}

function responseError(response, res) {
  try {
    const system = response.data.system || {}

    // 响应成功时，记录到日志
    const content = {
      _url_: response.config.url,
      param: response.config.data,
      retcode: res.result,
      retmsg: res.res_info,
      trace_id: system.trace_id || ''
    }
    interfaceMonitor(content, type[1], 0)
    errReport(content, { trace_id: system.trace_id || '' })

    Toast(`[${res.result}] ${res.res_info || ''}`)
  } catch (e) {
    console.log(e)
  }
}

// 响应失败
function responseFail(err) {
  const config = err.config

  // 响应失败时，记录到日志
  const content = {
    _url_: config.url,
    param: config.data
  }
  interfaceMonitor(content, type[1], 0)

  Toast(`${err.message} in '${err.config.url}'`)
  return Promise.reject(err)
}

// 注入请求和响应拦截
const axiosInstance = axios.create(AXIOS_DEFAULT_CONFIG)
axiosInstance.interceptors.request.use(requestSuccess, requestFail)
axiosInstance.interceptors.response.use(responseSuccess, responseFail)

export default (opt = {}) => {
  options = opt
  return axiosInstance
}
